//
//  PayViewController.m
//  JxCarios
//
//  Created by xcq on 15/2/5.
//  Copyright (c) 2015年 xiongchuanqi. All rights reserved.
//

#import "PayViewController.h"
#import "payTypeSeleteTableViewCell.h"
#import "PayWriteScoreTableViewCell.h"
#import "ReplaceDriveDetailPriceCell.h"

static NSString *checkCell = @"payTypeSelete";
static NSString *inputCell = @"payWriteScore";
static NSString *priceCell = @"detailprice";
@interface PayViewController () <payWrite,pushMessegeToSuper,UIAlertViewDelegate>
@property (retain, nonatomic ) PayWriteScoreTableViewCell *pay;

@end

@implementation PayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initAbout];
}

- (void)initAbout {
    self.title = @"支付";
    _pay_way = @"1";

    if (!_cellArr) {
        _cellArr = [NSMutableArray new];
    }
    [self showNavBarWithRightTitle:nil andRightAction:nil andLeftAction:nil andCustom:NO];
    REGISTCELL(@"payTypeSeleteTableViewCell", checkCell);
    REGISTCELL(@"PayWriteScoreTableViewCell", inputCell);
    REGISTCELL(@"ReplaceDriveDetailPriceCell", priceCell);
    _checkView.backgroundColor = [UIColor whiteColor];
    _lineView.backgroundColor = UICOLOR_MAKE_RGB(239, 238, 244);
 
   
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)setCountPrice:(double)countPrice{
    NSLog(@"1");
    _countPrice = countPrice;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.view.backgroundColor = UICOLOR_MAKE_RGB(236, 236, 236);
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    self.tableView.tableFooterView = view;
    if (!_carAround) {
        _carAround = [CarAroundDataSource dataSourceWithRequestor:self];
    }
    [_carAround getCurrenScore:^(id result) {
        _vb = [result customObjectForkey:@"vb"];
        [self.tableView reloadData];
    } anfFail:^(id result) {
        [self errorChuli];
    }];
}

- (void)errorChuli {
    [self.navigationController.view makeToast:@"vb获取失败!" duration:1.0f position:TOP_POINT];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableView delegate & dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return _buyShopArr.count <= 0 ? 0 : _buyShopArr.count+1;
            break;
        case 1:
            return 2;
            break;
        case 2:
            return 2;
            break;
        default:
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case  0:
            return 44;
            break;
        case 1:
            return 44;
            break;
        case 2:
            return 60;
            break;
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0:
        {
            ReplaceDriveDetailPriceCell *price = [tableView dequeueReusableCellWithIdentifier:priceCell forIndexPath:indexPath];
            price.selectionStyle = UITableViewCellSelectionStyleNone;
            if (indexPath.row == 0) {
                price.priceLabel.font = [UIFont systemFontOfSize:16.0f];
                price.timeLabel.font = [UIFont systemFontOfSize:16.0f];
                price.priceLabel.textColor = [UIColor redColor];
                price.timeLabel.textColor = [UIColor redColor];
                price.timeLabel.text = @"总计";
                price.priceLabel.text = [NSString stringWithFormat:@"%.2f",_countPrice];
                price.line.hidden = YES;
                price.linePrice.hidden = YES;
            }else{
                price.priceLabel.font = [UIFont systemFontOfSize:14.0f];
                price.timeLabel.font = [UIFont systemFontOfSize:14.0f];
                price.priceLabel.textColor = BTN_COLOR;
                price.timeLabel.textColor = [UIColor blackColor];
                price.priceLabel.text = [[_buyShopArr objectAtIndex:indexPath.row-1] customObjectForkey:@"CHEAP_PRICE"];
                price.converScopreLabel.hidden = NO;
                [price setVb:[[_buyShopArr objectAtIndex:indexPath.row-1] customObjectForkey:@"IS_VB"]];
                price.timeLabel.text = [[_buyShopArr objectAtIndex:indexPath.row-1] customObjectForkey:@"GOOD_NAME"];
                price.line.hidden = YES;
            }
             if (![price.timeLabel.text isEqualToString:@"总计"] && _cellArr.count < _buyShopArr.count) {
                [_cellArr addObject:price];
            }
            return price;
            break;
        }
        case 1:
        {
            if (indexPath.row == 0) {
                ReplaceDriveDetailPriceCell *price = [tableView dequeueReusableCellWithIdentifier:priceCell forIndexPath:indexPath];
                price.selectionStyle = UITableViewCellSelectionStyleNone;
                price.priceLabel.font = [UIFont systemFontOfSize:15.0f];
                price.timeLabel.font = [UIFont systemFontOfSize:15.0f];
                price.priceLabel.textColor = [UIColor blackColor];
                price.timeLabel.textColor = [UIColor blackColor];
                price.timeLabel.text = @"当前积分";
                price.line.hidden = YES;
                price.linePrice.hidden = YES;
                price.priceLabel.text = _vb;
                price.line.hidden = YES;
                return price;
            }else{
                _pay = [tableView dequeueReusableCellWithIdentifier:inputCell forIndexPath:indexPath];
                _pay.action = @selector(inputTextFieldDelegate:);
                _pay.vb = _vb;
                _pay.target = self;
                 return _pay;
                
            }
            break;
        }
        case 2:
        {
            payTypeSeleteTableViewCell *selete = [tableView dequeueReusableCellWithIdentifier:checkCell forIndexPath:indexPath];
            selete.selectionStyle = UITableViewCellSelectionStyleNone;
            selete.pushDelegate = self;
            selete.delegate = _pay;
            if (!_checkCellArr) {
                _checkCellArr = [NSMutableArray new];
            }
            if (indexPath.row == 0) {
                //TODO:图片未设置
                selete.seleteTypeImg.image = [UIImage imageNamed:@"zhifu"];
                selete.seleteTypeName.text = @"当面付";
                selete.seleteTypeDetail.text = @"至商家处当面付款,无积分奖励";
                selete.bol = YES;
                if(_checkCellArr.count != 2){
                    [_checkCellArr addObject:selete];
                }
            }else{
                selete.bol = NO;
                selete.seleteTypeImg.image = [UIImage imageNamed:@"zhifu-01"];
                selete.seleteTypeName.text = @"支付宝";
                selete.checkBtn.selected = YES;
                selete.seleteTypeDetail.text = @"推荐开通支账户用户使用,积分奖励";
                if(_checkCellArr.count != 2){
                    [_checkCellArr addObject:selete];
                }
            }
            return selete;
            break;
        }
     }
    
    return nil;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        payTypeSeleteTableViewCell *cell = [_checkCellArr objectAtIndex:indexPath.row];
        [cell seletePayType:cell.checkBtn];
    }
}

#pragma mark - inputCell delegaet
- (void)inputTextFieldDelegate:(NSString *)str {
   
    double price = [str doubleValue];
    double cellPrice = 0.0f;
    double result = 0.0f;
    ReplaceDriveDetailPriceCell *temp = nil;
    for (temp in _cellArr) {
        temp.scope = @"0";
        temp.linePrice.text = @"";
        if (temp.is_Vb) {
            cellPrice = [temp.priceLabel.text doubleValue] * 100;
            if (cellPrice <= price) {
                result = price - cellPrice;
                price = result;
                NSString *str = @"使用";
                temp.scope = [NSString stringWithFormat:@"%.0f",cellPrice];
                temp.converScopreLabel.text = [[str stringByAppendingString:[NSString stringWithFormat:@"%.0lf积分",cellPrice]] stringByAppendingString:[NSString stringWithFormat:@"抵扣%.2f元",[temp.priceLabel.text doubleValue]]];
            }else{
                if (price == 0) {
                    break;
                }
                NSString *str = @"使用";
                temp.scope = [NSString stringWithFormat:@"%.0f",price];
                temp.converScopreLabel.text = [[str stringByAppendingString:[NSString stringWithFormat:@"%.0lf积分",price]] stringByAppendingString:[NSString stringWithFormat:@"抵扣%.2f元",price/100]];
            }
        }
    }
}


#pragma mark - checkCell delegate 
- (void)pushSelfToView:(payTypeSeleteTableViewCell *)cell andType:(BOOL)bol andSelete:(BOOL)selete{
    payTypeSeleteTableViewCell *temp = nil;
     if (cell == (payTypeSeleteTableViewCell *)[_checkCellArr firstObject]) {
        temp = (payTypeSeleteTableViewCell *)[_checkCellArr lastObject];
    }else{
        temp = [_checkCellArr firstObject];
    }
    
    temp.checkBtn.selected = NO;
    if (bol) { //当面付
        _pay_way = @"0";
        [temp.delegate checkCallBack:temp andSeleted:NO andDetail:@"当面付无法使用积分"];//如果选择的支付宝。手动用当面付的cell调用代理方法打开输入cell的enable

     }else{//支付宝
         _pay_way = @"1";
         [temp.delegate checkCallBack:temp andSeleted:YES andDetail:@"请输入可用积分"];//如果选择的支付宝。手动用当面付的cell调用代理方法打开输入cell的enable
     }
    NSLog(@"%@",_pay_way);
}

- (void)viewWillAppear:(BOOL)animated{
    [self.view hideToastActivity];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 20;
    }else{
        return 30;
    }
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 30)];
    view.backgroundColor = UICOLOR_MAKE_RGB(236, 236, 236);
    if (section == 1) {
       
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 60, 20)];
        label.font = [UIFont systemFontOfSize:13.0f];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"使用积分";
        [view addSubview:label];
        return view;
    }else if(section == 2){
       
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 80, 20)];
        label.font = [UIFont systemFontOfSize:13.0f];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentLeft;
        label.text = @"选择支付方式";
        [view addSubview:label];
        return view;
    }
    
    return view;
 }

/*
 * order          [{good_id:'',price:'',pay_money:'',use_point:''},..]	Jsonarray格式，代表商品详情，good_id是商品id，price是商品价格，pay_money是实付金额，use_point是实付v币数

 */
//返回数据:{"type":"imicreateorder","fl ag":"success","money":200,"order_state":"0","order_id":"112015013104069132"}
- (IBAction)submitAction:(id)sender {
    _priceSum = 0.0f;
    if(!_carAround){
        _carAround = [CarAroundDataSource dataSourceWithRequestor:self];
    }
     if(!_pro){
        _pro = [Product new];
    }
 
     __block  NSDictionary *param  = nil;
    _carAround.pay_away = _pay_way;
    _carAround.orderArr = [NSMutableArray new];
    
    dispatch_queue_t queue = dispatch_queue_create("barrier.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(queue, ^{
        for (__block int a = 0; a < _buyShopArr.count; a++ ) {
            NSDictionary *dic = [_buyShopArr objectAtIndex:a];
            
            ReplaceDriveDetailPriceCell *cell = (ReplaceDriveDetailPriceCell*)[_cellArr objectAtIndex:a];
            NSString *userPoint = cell.scope.length == 0 ? @"" : cell.scope;
            param =@{@"good_id":[dic customObjectForkey:@"ID"]
                      ,@"price":[dic customObjectForkey:@"CHEAP_PRICE"]
                      ,@"pay_money":[NSString stringWithFormat:@"%.2f",[cell.priceLabel.text doubleValue] - [cell.scope doubleValue] / 100]
                      ,@"use_point":userPoint };

            [_carAround.orderArr addObject:param];
        }
             [_carAround getShopId:^(id result) {
                 //0:
                 //1:
                 //2:
                 if ([[result customObjectForkey:@"order_state"] isEqualToString:@"1"]) {
                      [self.navigationController popViewControllerAnimated:YES];
                     [[NSNotificationCenter defaultCenter] postNotificationName:@"payTips" object:nil];
                     return ;
                 }
                 _priceSum += [[result customObjectForkey:@"money"] doubleValue];
                 if ([_pay_way isEqualToString:@"0"]) {
                     [self.navigationController popViewControllerAnimated:YES];
                     [[NSNotificationCenter defaultCenter] postNotificationName:@"payTips" object:nil];

                    return ;
                }
                    _pro.orderId = [result customObjectForkey:@"order_id"];
                    _pro.subject = @"购买商品";
                    _pro.body = @"商品列表";
                    _pro.price = [[result customObjectForkey:@"money"] doubleValue];
                    [self CreateOrderInfo:_pro
                                  tradeNo:[result customObjectForkey:@"order_id"]
                                 callback:^(NSDictionary *resultDic) {
                                      if ( [[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"])
                                      {
                                          [self.navigationController popViewControllerAnimated:YES];
                                          [[NSNotificationCenter defaultCenter] postNotificationName:@"payTips" object:nil];
                                          return ;
                                          
                                      }else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"4000"])
                                      {
                                         [self.navigationController.view makeToast:@"订单支付失败" duration:2.0f position:TOP_POINT];
                                      }else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6001"]){
                                         [self.navigationController.view makeToast:@"您中途取消了支付" duration:2.0f position:TOP_POINT];
                                      }else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6002"])
                                      {
                                          [self.navigationController.view makeToast:@"网络不通畅,请重试" duration:2.0f position:TOP_POINT];
                                      }
                                 }];
                
            } anfFail:^(id result) {
                
             }];
      
    });
}



-(void)networkingStartHandleWithRequestIdentifier:(RequestIdentifier)identifier{
    [self.view makeToastActivity];//现实加载中
    self.view.layer.cornerRadius = 8.0f;
}

-(void)networkingFailureHandleWithRequestIdentifier:(RequestIdentifier)identifier errorMessage:(NSString *)message{
    [self.view makeToast:message];
}


@end

